<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="入库状态" prop="receiptOrderStatus">
          <el-radio-group v-model="queryParams.receiptOrderStatus" @change="handleQuery">
            <el-radio-button :key="-2" :label="-2">
              全部
            </el-radio-button>
            <el-radio-button v-for="item in wms_receipt_status" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入库类型" prop="receiptOrderType">
          <el-radio-group v-model="queryParams.receiptOrderType" @change="handleQuery">
            <el-radio-button :key="-1" :label="-1">
              全部
            </el-radio-button>
            <el-radio-button v-for="item in wms_receipt_type" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入库单号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入入库单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="业务单号" prop="bizOrderNo">
          <el-input v-model="queryParams.bizOrderNo" placeholder="请输入业务单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">入库单</span></el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="receiptOrderList" border class="mt20" @expand-change="handleExpandExchange"
        :row-key="getRowKey" :expand-row-keys="expandedRowKeys" empty-text="暂无入库单" cell-class-name="vertical-top-cell">
        <el-table-column type="expand">
          <template #default="props">
            <div style="padding: 0 50px 20px 50px">
              <el-row>
                <el-col :span="12">
                  <h3>商品明细</h3>
                </el-col>
                <el-col :span="12" style="margin-top: 10px;">
                  <el-button style="margin-left: 600px;" type="primary" plain icon="Plus"
                    @click="receipt(props.row)">入库</el-button>
                </el-col>
              </el-row>
              <el-table ref="detaliRef" :data="props.row.details" v-loading="detailLoading[props.$index]"
                empty-text="暂无商品明细" @selection-change="handleSelectionChange">
                <el-table-column :selectable="selectable" type="selection" width="55" align="center" />
                <el-table-column label="商品名称">
                  <template #default="scope">
                    <div>{{ scope.row.item_name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="所属仓库" prop="warehouseId">
                  <template #default="scope">
                    <div>{{ scope.row.warehouse_name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="所属库区" prop="areaId">
                  <template #default="scope">
                    <div>{{ scope.row.area_name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="realQuantity" align="right">
                  <template #default="scope">
                    {{ scope.row.real_quantity }}
                  </template>
                </el-table-column>
                <el-table-column label="金额(元)" align="right">
                  <template #default="scope">
                    {{ scope.row.money }}
                  </template>
                </el-table-column>
                <el-table-column label="状态" align="right">
                  <template #default="scope">
                    <dict-tag :options="wms_receipt_status" :value="scope.row.receipt_order_status" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单号/业务单号" align="left" min-width="120" prop="orderNo" />
        <el-table-column label="总金额(元)" align="left" min-width="100" prop="payableAmount" />
        <!-- <template #default="{ row }">
            <div class="flex-space-between">
              <span>数量：</span>
              <el-statistic :value="Number(row.totalQuantity)" :precision="0" />
            </div>
            <div class="flex-space-between" v-if="row.totalAmount || row.totalAmount === 0">
              <span>金额：</span>
              <el-statistic :value="Number(row.totalAmount)" :precision="2" />
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="入库状态" align="center" prop="receiptOrderStatus" width="80">
          <template #default='scope'>
            <dict-tag :options="wms_receipt_status" :value="scope.row.receiptOrderStatus" />
          </template>
        </el-table-column>

        <el-table-column label="入库类型" align="center" prop="receiptOrderType" width="100">
          <template #default='scope'>
            <dict-tag :options="wms_receipt_type" :value="scope.row.receiptOrderType" />
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="left" prop="supplierName">
        </el-table-column>
        <el-table-column label="操作时间" align="left" width="150">
          <template #default="{ row }">
            <div>创建：{{ parseTime(row.createTime, '{mm}-{dd} {hh}:{ii}') }}</div>
            <div>更新：{{ parseTime(row.updateTime, '{mm}-{dd} {hh}:{ii}') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="left">
          <template #default="{ row }">
            <div>{{ row.createBy }}</div>
            <div v-if="row.updateBy">{{ row.updateBy }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" align="right" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" @click="handleGoDetail(scope.row)">{{
              expandedRowKeys.includes(scope.row.id) ? '收起' : '查看' }}</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button link type="primary" @click="dy(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <el-dialog :close-on-click-modal="false" title="请选择入库状态" v-model="open" width="50%">
      <el-form-item>
        <el-radio-group v-model="receiptData.receiptOrderStatus">
          <el-radio-button v-for="item in sta" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <div class="dialog-footer" slot="footer">
        <el-button type="primary" @click="updateStatus()">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="order">
import { delOrder, getOrder, listOrder, updateOrder, receiptOrder } from "@/api/wms/order";
import { reactive, ref, toRefs } from "vue";
import { getByIdDetail } from "@/api/wms/detail";
import printTemplate from 'print-template'

//打印
async function dy(row) {
  // 创建打印模板 
  let template = new printTemplate()
  //添加模板
  let yto = {
    name: 'yto', // 模板名称
    unit: 'mm',        // 尺寸  mm / px
    size: [76, 130],        // a4 或 [221,291]
    fixed: [          // 固定内容 比如：线条 、logo 广告、固定字体 
      // 个人觉得 制作一个透明的底图 不需要一条线一条线设置
      { type: 'line', x: 2, y: 12, length: 72 },
      { type: 'line', x: 2, y: 12, orientation: 'p', length: 116 },
      { type: 'line', x: 74, y: 12, orientation: 'p', length: 116 },
      { type: 'line', x: 2, y: 27, length: 72 },
      { type: 'line', x: 2, y: 35, length: 72 },
      { type: 'line', x: 2, y: 41, length: 52 },
      { type: 'line', x: 54, y: 35, orientation: 'p', length: 32 },
      { type: 'line', x: 54, y: 49, length: 20 },
      { type: 'line', x: 2, y: 59, length: 72 },
      { type: 'line', x: 2, y: 67, length: 72 },

      { type: 'text', default: '物料名', x: 7, y: 71, fontSize: '2.5', fontFamily: '微软雅黑', fontWeight: 700, fontStyle: 'normal', maxWidth: null, orientation: 'l', color: 'black' },
      { type: 'line', x: 20, y: 67, orientation: 'p', length: 43 },

      { type: 'text', default: '物料数量', x: 25, y: 71, fontSize: '2.5', fontFamily: '微软雅黑', fontWeight: 700, fontStyle: 'normal', maxWidth: null, orientation: 'l', color: 'black' },
      { type: 'line', x: 40, y: 67, orientation: 'p', length: 43 },
      { type: 'text', default: '物料单价', x: 44, y: 71, fontSize: '2.5', fontFamily: '微软雅黑', fontWeight: 700, fontStyle: 'normal', maxWidth: null, orientation: 'l', color: 'black' },
      { type: 'line', x: 60, y: 67, orientation: 'p', length: 43 },
      { type: 'text', default: '金额', x: 65, y: 71, fontSize: '2.5', fontFamily: '微软雅黑', fontWeight: 700, fontStyle: 'normal', maxWidth: null, orientation: 'l', color: 'black' },
      { type: 'line', x: 2, y: 77, length: 72 },

      { type: 'line', x: 2, y: 84, length: 72 },
      { type: 'line', x: 2, y: 89, length: 72 },
      { type: 'line', x: 2, y: 95, length: 72 },
      { type: 'line', x: 2, y: 100, length: 72 },
      { type: 'line', x: 2, y: 105, length: 72 },

      { type: 'line', x: 2, y: 110, length: 72 },
      { type: 'line', x: 2, y: 128, length: 72 },
      {
        type: 'text',          // 类型  文本 line / text / image / barcode / qrcode
        default: '货到\n付款',        // 默认值  \n 换行  或设置maxWidth大小
        x: 66,                  // x
        y: 2,                  // y
        fontSize: '3.8',         // 字体大小
        fontFamily: '微软雅黑',  // 字体类型   默认 '微软雅黑'
        fontWeight: 700,       // 字体宽度
        fontStyle: 'normal',    // 字体样式 normal / 斜体
        maxWidth: null,         // 最大换行宽度
        orientation: 'l',       // 方向 默认 l 横向  / p 竖向
        color: 'black'            // 字体颜色 (1.2.8版本新增)
      },
      {
        type: 'text',          // 类型  文本 line / text / image / barcode / qrcode
        default: '总金额:',        // 默认值  \n 换行  或设置maxWidth大小
        x: 57,                  // x
        y: 38,                  // y
        fontSize: '3.5',         // 字体大小
        fontFamily: '微软雅黑',  // 字体类型   默认 '微软雅黑'
        fontWeight: 700,       // 字体宽度
        fontStyle: 'normal',    // 字体样式 normal / 斜体
        maxWidth: null,         // 最大换行宽度
        orientation: 'l',       // 方向 默认 l 横向  / p 竖向
        color: 'black'            // 字体颜色 (1.2.8版本新增)
      },
      {
        type: 'text',          // 类型  文本 line / text / image / barcode / qrcode
        default: '创建时间:',        // 默认值  \n 换行  或设置maxWidth大小
        x: 5,                  // x
        y: 30,                  // y
        fontSize: '2.5',         // 字体大小
        fontFamily: '微软雅黑',  // 字体类型   默认 '微软雅黑'
        fontWeight: 700,       // 字体宽度
        fontStyle: 'normal',    // 字体样式 normal / 斜体
        maxWidth: null,         // 最大换行宽度
        orientation: 'l',       // 方向 默认 l 横向  / p 竖向
        color: 'black'            // 字体颜色 (1.2.8版本新增)
      },
      { type: 'text', x: 3, y: 42, default: '备注:', fontSize: '3.2' },
    ],
    data: {                    // 动态数据
      remark: { type: 'text', x: 8, y: 47, fontSize: 2.0 },
      receiptOrderNo: { type: 'barcode', x: 7, y: 13, format: 'CODE128A', width: 4, margin: 0, fontSize: 3.3, fontOptions: 'bold', displayValue: true, height: 13 },
      payableAmount: { type: 'text', x: 60, y: 44, fontSize: 2.8 },
      createTime: { type: 'text', x: 18, y: 30, fontSize: 2.8 },
      itemName: { type: 'text', x: 3, y: 80, fontSize: 2.7 },
      realQuantity: { type: 'text', x: 29, y: 80, fontSize: 2.7 },
      unitPrice: { type: 'text', x: 47, y: 80, fontSize: 2.7 },
      money: { type: 'text', x: 64, y: 80, fontSize: 2.7 },
    }
  }
  let orderData = {
    'receiptOrderNo': '',
    'remark': '',
    'payableAmount': 0,
    'createTime': null,
    'itemName': '',
    'realQuantity': '',
    'unitPrice': '',
    'money': ''
  }
  //传入数据
  console.log(row);

  getOrder(row.id).then(async response => {
    orderData.receiptOrderNo = response.data.receiptOrderNo
    orderData.remark = response.data.remark
    orderData.payableAmount = response.data.payableAmount
    orderData.createTime = response.data.createTime
    await getByIdDetail(row.receiptOrderNo).then(res => {
      res.rows.forEach(item => {
        orderData.itemName += item.item_name + '\n' + '\n'
        orderData.realQuantity += item.real_quantity + '\n' + '\n'
        orderData.unitPrice += item.unit_price + '\n' + '\n'
        orderData.money += item.money + '\n' + '\n'
      })
      console.log(orderData);

    })
    // 添加模板 
    template.push(yto)
    // 打印 
    template.print('yto', orderData).then(pdf => {
      // 返回 jspdf
      // blob 地址
      let uri = pdf.output('bloburi', { filename: '打印文件' });
      // 下载保存
      pdf.save('打印文件');
    })
  })
}

const { proxy } = getCurrentInstance();
const { wms_receipt_status, wms_receipt_type } = proxy.useDict("wms_receipt_status", "wms_receipt_type");
const state = wms_receipt_status;

const receiptOrderList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const single = ref(true);
const multiple = ref(true);
let row = reactive([]);
// 当前展开集合
const expandedRowKeys = ref([])
// 商品明细table的loading状态集合
const detailLoading = ref([])
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itemNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  row.value = selection;
}
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    receiptOrderType: -1,
    merchantId: undefined,
    bizOrderNo: undefined,
    totalAmount: undefined,
    receiptOrderStatus: -2,
  },
});

const { queryParams } = toRefs(data);

const receiptData = ref()
const re = ref()
const sta = ref([])

function receipt(rows) {
  console.log(row);
  if (rows.receiptOrderStatus == 5) {
    proxy.$modal.msgError("已完成入库");
  } else {
    if (row.value == null || row.value.length == 0) {
      proxy.$modal.msgError("请选择物料");
    } else {

      if (row.value.length > 1) {
        for (let i = 0; i < row.value.length; i++) {
          if (row.value[i].receipt_order_status != row.value[row.value.length - 1].receipt_order_status) {
            proxy.$modal.msgError("请选择状态相同的物料");
            return
          }
        }
      }
      open.value = true
      receiptData.value = Object.assign(re, rows)
      console.log(row.value[0]);
      sta.value = []

      state.value.forEach(element => {
        if (element.value > row.value[0].receipt_order_status) {
          sta.value.push(element)
          console.log(sta);
        }
        if (element.value == 0) {
          sta.value.push(element)
        }
      })
    }
  }
}

function updateStatus() {
  // if (row.value != null) {


  receiptData.value.details = null
  let edits = row.value
  receiptData.value['details'] = row.value
  for (let i = 0; i < edits.length; i++) {
    receiptData.value.details[i].areaId = edits[i].area_id
    receiptData.value.details[i].receiptOrderId = edits[i].receipt_order_id
    receiptData.value.details[i].itemId = edits[i].item_id
    receiptData.value.details[i].realQuantity = edits[i].real_quantity
    receiptData.value.details[i].remark = receiptData.value.remark
    receiptData.value.details[i].warehouseId = edits[i].warehouse_id
    console.log(receiptData.value);
  }
  // } 
  // else {
  //   let detalis = receiptData.value.details
  //   for (let i = 0; i < detalis.length; i++) {
  //     receiptData.value.details[i].areaId = detalis[i].area_id
  //     receiptData.value.details[i].receiptOrderId = detalis[i].receipt_order_id
  //     receiptData.value.details[i].itemId = detalis[i].item_id
  //     receiptData.value.details[i].realQuantity = detalis[i].real_quantity
  //     receiptData.value.details[i].remark = receiptData.value.remark
  //     receiptData.value.details[i].warehouseId = detalis[i].warehouse_id
  //   }
  // }

  proxy.$modal.msgSuccess("操作成功");
  receiptOrder(receiptData.value).then(response => {
    console.log(response);
    if (response.code == 200) {
      proxy.$modal.msgSuccess("操作成功");
    } else {
      proxy.$modal.msgSuccess("操作失败");
    }
    close();
    getList();
  })

}

//物料入库后设置禁用单选框
const selectable = (row) => {
  if (row.receipt_order_status !== 5) {
    return true;
  } else {
    return false
  }
};

const detaliRef = ref()
function close() {
  open.value = false
  proxy.$refs.detaliRef.clearSelection()
  receiptData.value = null

}

/** 查询入库单列表 */
function getList() {
  loading.value = true;
  const query = { ...queryParams.value }
  console.log(query);

  if (query.receiptOrderStatus === -2) {
    query.receiptOrderStatus = null
  }
  if (query.receiptOrderType === -1) {
    query.receiptOrderType = null
  }
  listOrder(query).then(response => {
    receiptOrderList.value = response.rows;
    total.value = response.total;
    for (let i = 0; i < total; i++) {
      detailLoading.value.push(false)
    }
    expandedRowKeys.value = []
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  console.log(queryParams.value);

  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push("/wms/orderInfo/index");
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.receiptOrderNo || ids.value;
  proxy.$modal.confirm('确认删除入库单【' + row.orderNo + '】吗？').then(function () {
    loading.value = true;
    delOrder(_ids).then(() => {
      proxy.$modal.msgSuccess("删除成功");
    }).finally(() => {
      loading.value = false;
      getList();
    });
  })
}

function handleUpdate(row) {
  if (row.receiptOrderStatus == 5) {
    proxy.$modal.msgError("已完成入库，不可修改");

  } else {
    console.log(row);

    proxy.$router.push({ path: "/wms/orderInfo/index", query: { id: row.id, receiptOrderNo: row.receiptOrderNo } });
  }
}

function handleGoDetail(row) {
  const index = expandedRowKeys.value.indexOf(row.id)
  if (index !== -1) {
    // 收起
    expandedRowKeys.value.splice(index, 1)
  } else {
    // 展开
    expandedRowKeys.value.push(row.id)
    loadReceiptOrderDetail(row)
  }
}



function handleExpandExchange(value, expandedRows) {
  if (!ifExpand(expandedRows)) {
    return
  }
  expandedRowKeys.value = expandedRows.map(it => it.id)
  loadReceiptOrderDetail(value)
}
//详情数据
function loadReceiptOrderDetail(row) {
  const index = receiptOrderList.value.findIndex(it => it.receiptOrderNo === row.receiptOrderNo)
  getByIdDetail(row.receiptOrderNo).then(res => {
    console.log(res);
    if (res.rows?.length) {
      receiptOrderList.value[index].details = res.rows
    }
  }).finally(() => {
    detailLoading.value[index] = false
  })
}

function ifExpand(expandedRows) {
  if (expandedRows.length < expandedRowKeys.value.length) {
    expandedRowKeys.value = expandedRows.map(it => it.id)
    return false;
  }
  return true
}

function getRowKey(row) {
  return row.id
}
getList();
</script>
<style lang="scss">
.el-statistic__content {
  font-size: 14px;
}

.el-table .vertical-top-cell {
  vertical-align: top
}
</style>
